/**
 * Created by zhoulin on 2019/4/3.
 */
var companyId = sessionStorageUtils.getJson(storageKey.sessionStorageKey.companyId);
var schoolId = sessionStorageUtils.getJson(storageKey.sessionStorageKey.schoolId);
var schoolMap = sessionStorageUtils.getJson(storageKey.sessionStorageKey.schoolMap);

var app = new Vue({
    el: '#app',
    data: {
        permissions: ['goodsSpec:add', 'goodsSpec:update'],//本页权限数组
        paramTemplateList: [],
        paramList: [],
        desc: '',
        info: {},
        schoolId: schoolId,
        schoolList: schoolMap,
    },
    //进入页面初始化方法
    created: function () {
        var that = this;
        that.initParamTemplate();
        var token = sessionStorageUtils.getJson(storageKey.sessionStorageKey.token);
        if (empty(token)) {
            layer.msg("<span style='color:red'>登录超时！请重新登录！</span>", {time: 1500, icon: 5});
            setTimeout(function () {
                window.location.href = _LOGIN_PAGE;
            }, 1200);

            return;
        }
        if (!empty(aGET.id)) {
            that.getInfoById(aGET.id);
        }
    },
    methods: {
        //权限控制
        permission: function (index) {
            return (_PERMISSIONS.indexOf(this.permissions[index]) != -1);
        },
        initParamTemplate: function () {
            var that = this;
            // var url = _HOST + _API.product_goodsParam_getParents + "?companyId=" + companyId;
            var url = _HOST + _API.product_goodsParam_getParents;
            Get(that, url).then(function (res) {
                if (res.success) {
                    that.paramTemplateList = res.list;
                }
            });
        },
        getInfoById: function (id) {
            var that = this;
            Get(that, _HOST + _API.product_goodsSpec_getById + "?id=" + id)
                .then(function (response) {
                    // 响应成功回调
                    console.log(response);
                    if (response) {
                        if (response.success) {
                            var list = response.data;
                            that.info = list;
                            for (var item in list) {
                                /*if (item == 'status') {
                                    $("#Form select[name='status']").val(list[item]);
                                }*/
                                if (item == 'imgs') {
                                    initFilesUpload(list[item]);
                                }
                                if (item == 'params') {
                                    that.paramList = list[item];
                                }
                            }
                            $("#Form").data('bootstrapValidator').destroy();
                            $('#Form').data('bootstrapValidator', null);
                            Validator();
                        } else {
                            layer.msg(response.msg, {time: 1500, icon: 5});
                        }
                    }
                })
        },
        // 添加
        add: function () {
            var that = this;
            that.info.companyId = companyId;
            that.info.params = that.paramList;
            that.info.imgIds = $('#uploadImgs').getImgIdArr();
            //console.log(param)
            Post(that, _HOST + _API.product_goodsSpec_add, that.info, true, that.permissions[0])
                .then(function (response) {
                    // 响应成功回调
                    console.log(response);
                    if (response) {
                        if (response.success) {
                            layer.msg(response.msg, {time: 1500, icon: 1});
                            // 添加数据
                            var info = sessionStorageUtils.getParam(storageKey.sessionStorageKey.goods.goodsSpecList);
                            if (!empty(response.id)) {
                                info= info + ',' +response.id;
                                sessionStorageUtils.setParam(storageKey.sessionStorageKey.goods.goodsSpecList, info);
                            }
                            setTimeout(function () {
                                // window.parent.location.reload(); //刷新父页面
                                parent.layer.closeAll();
                            }, 1500)
                        } else {
                            layer.msg(response.msg, {time: 1500, icon: 5});
                        }
                    }
                    $("#Form").data('bootstrapValidator').destroy();
                    $('#Form').data('bootstrapValidator', null);
                    Validator();
                })
        },
        // 修改
        update: function () {
            var that = this;
            that.info.companyId = companyId;
            that.info.params = that.paramList;
            that.info.imgIds = $('#uploadImgs').getImgIdArr();
            // console.log(param)
            Post(that, _HOST + _API.product_goodsSpec_update, that.info, true, that.permissions[1])
                .then(function (response) {
                    // 响应成功回调
                    console.log(response);
                    if (response) {
                        if (response.success) {
                            layer.msg(response.msg, {time: 1500, icon: 1});
                            setTimeout(function () {
                                // window.parent.location.reload(); //刷新父页面
                                parent.layer.closeAll();
                            }, 1500)
                        } else {
                            layer.msg(response.msg, {time: 1500, icon: 5});
                        }
                    }
                    $("#Form").data('bootstrapValidator').destroy();
                    $('#Form').data('bootstrapValidator', null);
                    Validator();
                })
        },
        // 改变参数模板
        changeParamTemplate: function () {
            var that = this;
            var paramTemplateId = $("#Form select[name='paramTemplateId']").val();
            that.paramList = [];
            if (!empty(paramTemplateId)) {
                Get(that, _HOST + _API.product_goodsParam_getchildren + "?parenId=" + paramTemplateId)
                    .then(function (response) {
                        // 响应成功回调
                        console.log(response);
                        if (response) {
                            if (response.success) {
                                var list = response.list;
                                var tmpArr = [];
                                for (let i = 0; i < list.length; i++) {
                                    var tmp = {};
                                    tmp.paramId = list[i].id;
                                    tmp.paramName = list[i].name;
                                    tmp.paramInfo = list[i].param;
                                    tmp.companyId = companyId;
                                    tmpArr.push(tmp);
                                }
                                that.paramList = tmpArr;
                            } else {
                                layer.msg(response.msg, {time: 1500, icon: 5});
                            }
                        }
                    })
            }
        },
        getParams: function () {
            var that = this;
            console.log(that.paramList);
        }
    },
});


function initFilesUpload(imgs) {
    var uploadImgs = $('#uploadImgs').diyUpload({
        url: _HOST + _API.common_file_ossUpload,
        begin: function() {
            layer.load(0, {shade: false});
        },
        success: function (data) {
            layer.closeAll();
            console.log("图片上传成功！");
        },
        error: function (err) {
            layer.closeAll();
            layer.msg(err, {time: 1500, icon: 5});
            console.log("图片上传失败！");
        },
        headers: {
            'Authorization': sessionStorageUtils.getJson(storageKey.sessionStorageKey.token),
        },
        previewArr: imgs,
        thumb: {
            width: 120,
            height: 90,
            quality: 100,
            allowMagnify: true,
            crop: true,
            type: "image/jpeg"
        }
    });
}

$(function () {
    if (empty(aGET.id)) {
        initFilesUpload('');
    }
});

$('#Form').data('bootstrapValidator', null);
Validator();

function Validator() {
    $('#Form').bootstrapValidator({
        fields: {
            name: {
                validators: {
                    notEmpty: {
                        message: '名称不能为空'
                    },
                    stringLength: {
                        max: 50,
                        message: '名称长度最多50个字符'
                    },
                }
            },
            sort: {
                validators: {
                    notEmpty: {
                        message: '排序不能为空'
                    },
                }
            },
        }
    }).on('success.form.bv', function (e) {
        // Prevent form submission
        e.preventDefault();
        if (empty(aGET.id)) {
            app.add();
        } else {
            app.update();
        }
    });
}
